#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use POSIX;
use Logs;
use FindBin qw( $RealBin );
use Temp;
use MIME::Base64;
use File::Basename;
use Code;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象

    # projectid addr ticketid rely name(版本信息可能为空) temp(logs目录下的临时目录名) uuid

=cut

return sub
{
    my %param = @_;

    my ( $db, $logs, $projectid, $addr, $ticketid, $rely, $name, $temp, $uuid )
        = @param{qw(db logs projectid addr ticketid rely name temp uuid )};

    $logs = Logs->new( 'code.build.dump.pull.pkgrsync' ) unless $logs;

    my $temppath = "$RealBin/../logs/$temp/$uuid";
    if( -d $temppath )
    {
        my $user = `id -un`;chop $user;
        my $sudo = $user eq 'root' ? '' : 'sudo ';
        $logs->die( "clean old temppath fail:$!" ) if system "${sudo}rm -rf '$temppath'";
    }

    $logs->die( "mkdir temppath fail:$!" ) if system "mkdir -p '$temppath'";

    my ( $path, $tarname ) = ( "$RealBin/../pkgrsync", 'wk_ci_IgnoreOthers_KeepThisFileOnly' );

    $name = '' unless defined $name;
    unless( $name )
    {
        for my $file ( map{ basename $_ } sort glob "$path/repo/$projectid@*" )
        {
            next unless $file =~ /^$projectid@(.+)$/;
            $name = $1;
        }
        print "nofind version\n";
    	$logs->die( "nofind name" ) unless $name;
    }
    print "version: $name\n";
    $logs->die( "name format error" ) unless $name =~ /^[a-zA-Z0-9\.\-_]+$/;
    $logs->die( "clone error:$!" ) if system "cd '$temppath' && rm -rf data info && mkdir data && mkdir info && cp $path/repo/$projectid\@$name data/$tarname && tar -tf data/$tarname && echo '$name' > info/version";

    my $tagger;
    if ( -f "$path/mail/$projectid\@$name" )
    {
        $tagger = `cat '$path/mail/$projectid\@$name'`;
        chomp $tagger;
    }

    unless( defined $tagger && $tagger =~ /^[a-zA-Z0-9\.\@\-_]+$/ )
    {
        print "get tagger fail,Switch to default: open-c3\@org\n";
        $tagger = 'open-c3@org';
    }

    $logs->die( "write tagger info fail:$!" )if system "echo '$tagger' > '$temppath/info/tagger'";
    $logs->die( "write taginfo info fail:$!" )if system "echo '${tagger}_${name}' > '$temppath/info/taginfo'";
}


